package com.h.cheng.pselector.ui;

import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.h.cheng.pselector.R;
import com.h.cheng.pselector.base.BaseRecAdapter;
import com.h.cheng.pselector.base.BaseRecViewHolder;
import com.h.cheng.pselector.base.load.PSConfig;
import com.h.cheng.pselector.base.load.PSManager;
import com.h.cheng.pselector.bean.FileMedia;
import com.h.cheng.pselector.utils.FileUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileViewActivity extends AppCompatActivity implements View.OnClickListener {

    private RelativeLayout back;
    private TextView tv_simple_title;
    private TextView tv_path;
    private RecyclerView rv_file;
    private TextView tv_back;
    private String baseDir;
    private FileAdapter adapter;
    private Context context;
    private RelativeLayout rl_title;
    private TextView tv_select_all;
    private TextView tv_shear;
    private TextView tv_delete;
    private TextView tv_more;
    private LinearLayout ll_file_tools;
    private boolean isSelectall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_view);
        context = this;
        initView();
        addListener();
        initData();
    }

    private void addListener() {
        adapter.setItemClickListener(new BaseRecAdapter.onItemClickListener() {
            @Override
            public void onItemClick(BaseRecAdapter ad, View view, int position) {

                List<FileMedia> list = ad.getData();

                if (adapter.isShowSelect()) {
                    if (list.get(position).isSelected()) {
                        list.get(position).setSelected(false);
                    } else {
                        list.get(position).setSelected(true);
                    }
                    ad.notifyDataSetChanged();

                } else {
                    if (list.get(position).isDir()) {

                        if (list.get(position).getCount() == 0) {
                            return;
                        }
                        baseDir = list.get(position).getPath();

                        updataDir(false);
                    }
                }


            }
        });

        adapter.setItemLongClickListener(new BaseRecAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseRecAdapter ad, View view, int position) {
                if (adapter.isShowSelect()) {
                    adapter.setShowSelect(false);
                    ll_file_tools.setVisibility(View.GONE);
                } else {
                    List<FileMedia> list = ad.getData();
                    list.get(position).setSelected(true);
                    adapter.setShowSelect(true);
                    ll_file_tools.setVisibility(View.VISIBLE);
                }
                ad.notifyDataSetChanged();


                return false;
            }
        });
    }

    private void initData() {
        if (AndPermission.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
        )) {
            // 有权限，直接do anything.
            initBaseDir();

            updataDir(false);

        } else {
            // 申请权限。
            AndPermission.with(this)
                    .requestCode(102)
                    .permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .send();
        }


    }

    private void updataDir(boolean isShowSelct) {
        List<FileMedia> listMedia = FileUtils.listFiles(baseDir);
        adapter.setShowSelect(isShowSelct);
        adapter.setNewData(listMedia);


        tv_path.setText(baseDir);

        if (ll_file_tools.getVisibility() == View.VISIBLE) {
            ll_file_tools.setVisibility(View.GONE);
        }
    }

    private void initBaseDir() {
        baseDir = getIntent().getStringExtra(PSConfig.FILE_PATH);
        if (TextUtils.isEmpty(baseDir)) {
            String state = Environment.getExternalStorageState();
            // 检查是否有存储卡
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                // 创建位置
                baseDir = Environment.getExternalStorageDirectory().getPath();
            }
        }

    }

    private void initView() {
        back = findViewById(R.id.back);
        tv_simple_title = findViewById(R.id.tv_simple_title);
        tv_path = findViewById(R.id.tv_path);
        rv_file = findViewById(R.id.rv_file);
        tv_back = findViewById(R.id.tv_back);
        tv_back.setOnClickListener(this);
        back.setOnClickListener(this);

        tv_simple_title.setText("文件选择器");

        adapter = new FileAdapter(null);
        rv_file.setLayoutManager(new LinearLayoutManager(context));
        rv_file.addItemDecoration(new DividerItemDecoration(context, RecyclerView.VERTICAL));
        rv_file.setAdapter(adapter);

        rl_title = findViewById(R.id.rl_title);
        rl_title.setOnClickListener(this);
        tv_select_all = findViewById(R.id.tv_select_all);
        tv_select_all.setOnClickListener(this);
        tv_shear = findViewById(R.id.tv_shear);
        tv_shear.setOnClickListener(this);
        tv_delete = findViewById(R.id.tv_delete);
        tv_delete.setOnClickListener(this);
        tv_more = findViewById(R.id.tv_more);
        tv_more.setOnClickListener(this);
        ll_file_tools = findViewById(R.id.ll_file_tools);
        ll_file_tools.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back) {
            finish();
        } else if (v.getId() == R.id.tv_back) {
            //上一级
            if (baseDir.equals(Environment.getExternalStorageDirectory().getPath())) {
                showToast("已经是初始目录了");
                return;
            }

            String tempPath = new File(baseDir).getParent();
            if (tempPath == null) {
                return;
            }

            baseDir = tempPath;

            updataDir(false);

        } else if (v.getId() == R.id.tv_select_all) {
            //全选
            List<FileMedia> list = adapter.getData();

            for (FileMedia media : list) {
                if (isSelectall) {
                    media.setSelected(false);
                } else {
                    media.setSelected(true);
                }
            }
            isSelectall = !isSelectall;
            adapter.notifyDataSetChanged();

        } else if (v.getId() == R.id.tv_shear) {
            //剪切
        } else if (v.getId() == R.id.tv_delete) {
            //删除
            List<FileMedia> list = adapter.getData();
            List<String> listDelete = new ArrayList<>();
            for (FileMedia media : list) {
                if (media.isSelected()) {
                    listDelete.add(media.getPath());
                }
            }

            if (listDelete.size() == 0) {
                return;
            }
            for (String path : listDelete) {
                FileUtils.delete(path);
            }

            updataDir(false);

        } else if (v.getId() == R.id.tv_more) {
            //更多
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 只需要调用这一句，其它的交给AndPermission吧，最后一个参数是PermissionListener。
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                PSManager.getInstance().forCamera(FileViewActivity.this);
            } else if (requestCode == 101) {
                PSManager.getInstance().forAlbum(FileViewActivity.this);
            } else if (requestCode == 102) {

            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(FileViewActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(FileViewActivity.this, 300).show();
            }
        }
    };


    class FileAdapter extends BaseRecAdapter<FileMedia, FileViewHolder> {

        private boolean isShowSelect;

        public void setShowSelect(boolean showSelect) {
            isShowSelect = showSelect;
        }

        public boolean isShowSelect() {
            return isShowSelect;
        }

        public FileAdapter(List<FileMedia> list) {
            super(list);
        }

        @Override
        public void onHolder(FileViewHolder holder, final FileMedia bean, int position) {

            holder.tv_dir_name.setText(bean.getName());
            if (bean.isDir()) {
                holder.iv_dir.setBackgroundResource(R.mipmap.folder);
                holder.tv_dir_length.setText(bean.getCount() + "项");
            } else {
                holder.iv_dir.setBackgroundResource(R.mipmap.file);
                holder.tv_dir_length.setText(FileUtils.getFormatSize(bean.getSize()));
            }

            if (isShowSelect) {
                holder.cb_dir.setVisibility(View.VISIBLE);
                if (bean.isSelected()) {
                    holder.cb_dir.setBackgroundResource(R.mipmap.ic_select);
                } else {
                    holder.cb_dir.setBackgroundResource(R.mipmap.ic_unselect);
                }
            } else {
                holder.cb_dir.setVisibility(View.GONE);
            }

            holder.cb_dir.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (bean.isSelected()) {
                        bean.setSelected(false);
                    } else {
                        bean.setSelected(true);
                    }
                    notifyDataSetChanged();

                }
            });


        }

        @Override
        public FileViewHolder onCreateHolder() {
            return new FileViewHolder(getViewByRes(R.layout.item_dir));
        }
    }

    public class FileViewHolder extends BaseRecViewHolder {
        public View rootView;
        public ImageView iv_dir;
        public TextView tv_dir_name;
        public TextView tv_dir_length;
        public ImageView cb_dir;

        public FileViewHolder(View rootView) {
            super(rootView);
            this.rootView = rootView;
            this.iv_dir = rootView.findViewById(R.id.iv_dir);
            this.tv_dir_name = rootView.findViewById(R.id.tv_dir_name);
            this.tv_dir_length = rootView.findViewById(R.id.tv_dir_length);
            this.cb_dir = rootView.findViewById(R.id.cb_dir);
        }

    }

    private void showToast(String str) {
        if (TextUtils.isEmpty(str)) {
            return;
        }
        Toast.makeText(FileViewActivity.this, str, Toast.LENGTH_LONG).show();
    }
}
